#pragma once

#include <iostream>
#include "Protocol.hpp"

class Calculator
{
public:
    Calculator() {}
    ~Calculator() {}
    Response Execute(const Request &req)
    {
        Response resp;
        int x = req.X();
        int y = req.Y();
        switch (req.Oper())
        {
        case '+':
            resp.SetResult(x + y);
            break;
        case '-':
            resp.SetResult(x + y);
            break;
        case '*':
            resp.SetResult(x * y);
            break;
        case '/':
            {
                if (y == 0)
                    resp.SetCode(1); // 1表示除0错误
                else
                    resp.SetResult(x / y);
            }
            break;
        case '%':
            {
                if (y == 0)
                    resp.SetCode(2); // 2表示mod 0错误
                else
                    resp.SetResult(x % y);
            }
            break;
        default:
            resp.SetCode(3);  // 3表示不支持该运算
            break;
        }
        return resp;
    }
}cal;

std::string HandlerRequest(std::string& inbuffer)
{
    std::string resp_str;
    std::string content;
    while (Decode(inbuffer, &content))
    {
        if (content.empty())
            break;

        // 1、反序列化
        Request req;
        req.Deserialize(content);

        // DEBUG PRINT
        std::cout << "########################" << std::endl;
        req.Print();
        std::cout << "########################" << std::endl;

        // 2、业务处理
        Response resp = cal.Execute(req);

        // 3、序列化
        std::string resp_line;
        resp.Serialize(resp_line);

        // 4、添加长度说明
        Encode(resp_line);

        // 5、添加每一个应答
        resp_str += resp_line;
    }
    return resp_str;
}